import router from './index'
const cookie = useCookie()
const { start, done } = useNprogressLoading()
const { startLoading } = useFullLoading()
//全局前置守卫
router.beforeEach(async (to, from, next) => {
  const token = cookie.get('token')
  const userStore = useUserStore()
  start() //开启加载条
  // 没有登录强制跳回登录页
  if (!token && to.path !== '/login') {
    ElNotification({ title: '请先登录', type: 'error' })
    return next({ path: '/login' })
  }
  // 防止重复登录
  if (token && to.path === '/login') {
    ElNotification({ title: '请勿重复登录', type: 'warning' })
    return next(from.path || '/')
  }
  let hasNewRoutes = false
  // 如果用户登录了 自动获取用户信息 并存储全局
  if (token && !userStore.hasGetInfo) {
    let res: any = await userStore.useGetUserfn()
    hasNewRoutes = useAddRoutes(res.menus)
    userStore.$patch({ hasGetInfo: true })
    window.nextLoading === undefined && startLoading('正在加载中...')
  }
  useTitle(to.meta?.title) //设置页面标题
  // hasNewRoutes 如果一刷新就会丢失  router.addRoutes===router.push 所以要手动设置to.fullpath
  hasNewRoutes ? next(to.fullPath) : next()
})
//全局后置守卫
router.afterEach(() => done())
